package com.atguigu.tingshu.search.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
@Slf4j
public class ThreadPoolConfig {

    @Bean
    public ExecutorService executorService() {
        int processorsCount = Runtime.getRuntime().availableProcessors();
        log.info("该服务器的CPU核心数为：{}", processorsCount);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                processorsCount * 2,
                processorsCount * 10,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(2000),
                Executors.defaultThreadFactory(),
                //自定义拒绝策略
                (runnable, executor) -> {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    //再次将拒绝任务提交给线程池执行
                    executor.submit(runnable);
                }
        );
        //线程池创建,核心线程同时创建
        threadPoolExecutor.prestartAllCoreThreads();
        return threadPoolExecutor;
    }
}